package hzh;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Random;

@WebServlet(name = "AddMoviesServlet")
public class AddMoviesServlet extends HttpServlet {
    private static final long serialVersionUID = 1139723442711986380L;
    private static final String INSERT_TEMPLATE =
            "INSERT INTO movies (id,name, actors, type, score,price,des,pic) " +
                    "VALUES ('%s','%s', '%s', '%s', '%s', '%s', '%s', '%s')";
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        this.doPost(request, response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //get请求与将传过来的参数暴露，而post请求不会同时post不会对url的长度进行限制
        request.setCharacterEncoding("UTF-8");
        Random random = new Random();
        int id = random.nextInt(10000);
        String name = request.getParameter("name");//.request.getParameter()方法传递的数据，
        // 会从web客户端传到web服务器端，代表HTTP请求数据，该方法返回String类型的数据
        //request.setAttribute()和getAttribute()只是在web容器内部流转，仅仅是请求处理阶段
        String actors   = request.getParameter("actors");
        String type     = request.getParameter("tp");
        String score   = request.getParameter("score");
        String price    = request.getParameter("price");
        String describe = request.getParameter("describe");
        String pic= request.getParameter("pic");
        String sql = String.format(INSERT_TEMPLATE, id,name, actors, type, score,price, describe,pic);
        //String.format为生成一个列表
        System.out.println(sql);
        try {
            DBUtils.insert(sql);//准备插入表单信息
            response.sendRedirect("./list1.jsp");//跳转到listbook界面
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
